Thread: [HELP] find closes number from array??

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    4

    [HELP] find closes number from array??

    Hi,
    well i have a userinput for an integer. And i have to get sqrt of that number and find the closes number from array... and i dont rly know how to do that... can anyone help?

    heres the part for my input:
    Code:
    int poljubnostevilo;
    cin >> poljubnostevilo;
    cout <<endl;
    int koren = sqrt (poljubnostevilo);
    cout << koren << endl;
    and here's the function i use to fill in the array with prime numbers,.. etc...so this function also has to return the closest number from the array to the sqrt of the inputed integer...

    Code:
    int funkcijatri(int x, int n){
    
    n = 4;
    int praarray[x];
    int a=0;
    int sum;
        while(a<x){
                  n++;
                  if(IsPrime(n) && (n>=a)){
                                praarray[a] = n;
                                cout << praarray[a] << ", ";
                                sum+= praarray[a];
                                a++;
    
                               
                  }//konec if  
                
        }//konec while
        
        
        return sum/x;
           
    
    
        
    }
    Hope anyone can help me

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    An easy way ( or the only way? ) is to save a variable with the subtraction between userinput and each element of the array as you iterate through it. If the subtraction of userinput with each next element ( the absolute value, mind you ) is lower than the saved one, replace the old save with this one and also save the current index. When your iteration of the loop is over, you'll have the index of the closest value to userinput.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    4
    ok, i know this will sound that im lazy or something, but can you post a sample of the code to implement please?, im kinda new to c++ and im not sure if i know how do that what you wrote... so any implementation samples? -would be really great

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 03-03-2011, 04:23 PM
  2. Replies: 47
    Last Post: 11-16-2009, 10:18 PM
  3. Arrays, how to find if some number is the element of an array.
    By InvariantLoop in forum C++ Programming
    Replies: 14
    Last Post: 03-18-2006, 02:43 AM
  4. Replies: 2
    Last Post: 08-03-2003, 10:01 AM
  5. Can't find the lowest number in array?
    By Nate2430 in forum C++ Programming
    Replies: 1
    Last Post: 11-20-2001, 10:21 AM